package com.softdev.system.generator.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.util.Map;

/**
 * @author penghj
 * @date 2019/11/18 9:59
 */
@Slf4j
public class HttpClientUtil {

    private static CloseableHttpClient client;

    static {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(1000);
        connectionManager.setDefaultMaxPerRoute(1000);

        client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();
    }


    private HttpClientUtil() {}


    /**
     * 向指定URL发送POST方法的请求
     *
     * @param params 请求参数
     * @param url   发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String doPost(String url, Map<String, String> params) {
        try {
            HttpPost httpPost = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            CloseableHttpResponse response;
            if (params != null) {
                for (String key : params.keySet()) {
                    builder
                        .addPart(key, new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
                }
            }
            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);
            // 发起请求 并返回请求的响应
            response = client.execute(httpPost, HttpClientContext.create());
            return EntityUtils.toString(response.getEntity(), "utf-8");

        } catch (Exception e) {
            log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
        }
        return null;
    }

}